﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace UserControlLib
{
    /// <summary>
    /// 水印文本框的实现逻辑,通过后台代码控制实现
    /// </summary>
    public partial class WatermarkTextBoxBG : TextBox
    {
        private TextBlock _watermark;
        private AdornerLayer _adornerLayer;
        private const string watermarkText = "请输入内容";//默认水印内容
        public WatermarkTextBoxBG()
        {
            InitializeComponent();
            //注册加载事件
            this.Loaded += new RoutedEventHandler(WatermarkTextBoxBG_Loaded);
            //注册获取焦点事件
            this.GotFocus += new RoutedEventHandler(WatermarkTextBoxBG_GotFocus);
            //注册失去焦点事件
            this.LostFocus += new RoutedEventHandler(WatermarkTextBoxBG_LostFocus);
            //注册文本变化事件
            this.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
        }

        /// <summary>
        ///依赖属性水印内容
        /// </summary>
        public string Watermark
        {
            get
            {
                string result = (string)GetValue(WatermarkProperty);
                if (string.IsNullOrEmpty(result))
                {
                    result = watermarkText;
                }
                return result;
            }
            set { SetValue(WatermarkProperty, value); }
        }

        public static readonly DependencyProperty WatermarkProperty =
            DependencyProperty.Register("Watermark", typeof(string), typeof(WatermarkTextBoxBG), new PropertyMetadata(watermarkText, OnWatermarkChanged));

        private static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as WatermarkTextBoxBG;
            if (control != null && control._watermark != null)
            {
                control._watermark.Text = e.NewValue.ToString();
            }
        }

        public Brush WaterMarkForeground
        {
            get { return (Brush)GetValue(WaterMarkForegroundProperty); }
            set { SetValue(WaterMarkForegroundProperty, value); }
        }
        public static readonly DependencyProperty WaterMarkForegroundProperty =
           DependencyProperty.Register("WaterMarkForeground", typeof(Brush), typeof(WatermarkTextBoxBG),
               new PropertyMetadata(Brushes.LightGray, OnWaterMarkForegroundChanged));

        private static void OnWaterMarkForegroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as WatermarkTextBoxBG;
            if (control != null && control._watermark != null)
            {
                control._watermark.Foreground = (Brush)e.NewValue;
            }
        }

        /// <summary>
        /// 圆角
        /// </summary>
        public static readonly DependencyProperty CornerRadiusProperty =
       DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(WatermarkTextBoxBG),
           new PropertyMetadata(new CornerRadius(0), OnCornerRadiusChanged));

        private static void OnCornerRadiusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as WatermarkTextBoxBG;
            if (control != null)
            {
                control.CornerRadius = (CornerRadius)e.NewValue;
            }
        }

        public CornerRadius CornerRadius
        {
            get { return (CornerRadius)GetValue(CornerRadiusProperty); }
            set { SetValue(CornerRadiusProperty, value); }
        }

        public Brush Foreground
        {
            get { return (Brush)GetValue(ForegroundProperty); }
            set { SetValue(ForegroundProperty, value); }
        }
        /// <summary>
        /// 前景色
        /// </summary>
        public static readonly DependencyProperty ForegroundProperty =
            TextBox.ForegroundProperty.AddOwner(typeof(WatermarkTextBoxBG),
                new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnForegroundChanged));


        private static void OnForegroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as WatermarkTextBoxBG;
            if (control != null)
            {
                control.Foreground = (Brush)e.NewValue;
                control.UpdateWatermarkVisibility(); // 确保当前状态下水印颜色正确
            }
        }

        void WatermarkTextBoxBG_Loaded(object sender, RoutedEventArgs e)
        {
            _adornerLayer = AdornerLayer.GetAdornerLayer(this);
            if (_adornerLayer != null)
            {
                _watermark = new TextBlock
                {
                    Text = Watermark,
                    Foreground = WaterMarkForeground,
                    IsHitTestVisible = false,
                    Visibility = string.IsNullOrEmpty(this.Text) ? Visibility.Visible : Visibility.Hidden
                };
                var dif = (this.ViewportHeight - FontSize) / 2;
                _watermark.Margin = new Thickness(5, dif, 0, 0);
                var adorner = new AdornerDecorator(this, _watermark);
                _adornerLayer.Add(adorner);
            }
        }

        void WatermarkTextBoxBG_GotFocus(object sender, RoutedEventArgs e)
        {
            if (this.Text == Watermark)
            {
                this.Text = string.Empty;
            }
            UpdateWatermarkVisibility();
        }
        void WatermarkTextBoxBG_LostFocus(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.Text))
            {
                this.Text = string.Empty;
            }
            UpdateWatermarkVisibility();
        }
        void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            UpdateWatermarkVisibility();
        }

        private void UpdateWatermarkVisibility()
        {
            if (_watermark != null)
            {
                if (string.IsNullOrWhiteSpace(this.Text))
                {
                    _watermark.Visibility = Visibility.Visible;
                    _watermark.Foreground = WaterMarkForeground;
                }
                else
                {
                    _watermark.Visibility = Visibility.Hidden;
                }
            }
        }
    }

    // AdornerDecorator 类用于将水印添加到 AdornerLayer
    internal class AdornerDecorator : Adorner
    {
        private readonly UIElement _adornedElement;
        private readonly TextBlock _watermark;

        public AdornerDecorator(UIElement adornedElement, TextBlock watermark)
            : base(adornedElement)
        {
            _adornedElement = adornedElement;
            _watermark = watermark;
            _watermark.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            AddVisualChild(_watermark);
        }

        protected override int VisualChildrenCount => 1;

        protected override Visual GetVisualChild(int index)
        {
            return _watermark;
        }

        protected override Size MeasureOverride(Size constraint)
        {
            // 测量水印的实际尺寸
            _watermark.Measure(constraint);
            return _watermark.DesiredSize; // 返回水印的实际尺寸
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            // 让 TextBlock 自己处理居中对齐
            _watermark.Arrange(new Rect(finalSize));
            return finalSize;
        }
    }
}
